<template>
  <div class="app-container-flex asset-setting-dict">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :image-field="formInfo.imageField"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            :list-type-info="listTypeInfo"
          >
            <template v-slot:form-deviceTypeValue>
              <el-input
                v-model="formInfo.data.deviceTypeValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择医疗器械分类目录"
              >
                <template #append>
                  <el-icon @click="openDeviceTypeWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
            <!--资产分类-->
            <template v-slot:form-assetTypeValue>
              <el-input
                v-model="formInfo.data.assetTypeValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择资产分类"
              >
                <template #append>
                  <el-icon @click="openAssetClassifyWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-financeTypeValue>
              <el-input
                v-model="formInfo.data.financeTypeValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择资产财务类别"
              >
                <template #append>
                  <el-icon @click="openFinanceTypeWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-deprMonthsLimit>
              <el-input-number
                style="width: 40%"
                v-model.lazy="formInfo.data.deprYearsLimit"
                clearable
                controls-position="right"
                :precision="0"
                :min="0"
                :max="999999"
              />
              年
              <el-input-number
                style="width: 40%"
                v-model.lazy="formInfo.data.deprMonthsLimit"
                clearable
                controls-position="right"
                :precision="0"
                :min="0"
                :max="12"
              />
              月
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>证照信息</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="licenseInfo.ref"
            :data="licenseInfo.data"
            :field-list="licenseInfo.fieldList"
            :rules="licenseInfo.rules"
            :label-width="licenseInfo.labelWidth"
            :list-type-info="listTypeInfo"
          >
            <template v-slot:form-licenseNumber>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择证照"
                v-model="licenseInfo.data.licenseNumber"
              >
                <template #append>
                  <el-icon @click="openLicenseList"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <Select-setting-category
        v-if="selectSettingCategoryInfo.visible"
        v-model:showDialog="selectSettingCategoryInfo.visible"
        :saveEmpty="true"
        :check-box="false"
        :highlight-row="true"
        @callback="selectSettingCategoryInfoCallBack"
      />
      <SelectAssetClassify
        v-if="selectAssetClassifyInfo.visible"
        v-model:showDialog="selectAssetClassifyInfo.visible"
        :saveEmpty="true"
        :check-box="false"
        :highlight-row="true"
        @callback="selectAssetClassifyInfoCallBack"
      />

      <SelectSettingClassification
        v-if="selectSettingClassificationInfo.visible"
        v-model:showDialog="selectSettingClassificationInfo.visible"
        :saveEmpty="true"
        :check-box="false"
        :highlight-row="true"
        @callback="selectSettingClassificationInfoCallBack"
      />

      <select-license
        v-if="selectLicenseInfo.visible"
        @callback="selectLicenseCallback"
        :saveEmpty="true"
        :query="selectLicenseInfo.query"
        v-model:showDialog="selectLicenseInfo.visible"
      />
    </NewFullScreen>
  </div>
</template>

<script setup name="assetDictModify">
import utils from '@/common/js/utils' // 公共方法
import {
  detailEquipmentArchives,
  createEquipmentArchives,
  updateEquipmentArchives,
} from '@/api/equipment'
import { getCategoryDetailsById } from '@/api/asset'
import { getCoreCodeStatus, getUnitAll, getBrandAll } from '@/api/core'
import axios from 'axios'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [String, Number],
  },
  title: {
    type: String,
  },
})
const formInfo = reactive({
  ref: null,
  data: {
    deprConvention: 0,
    residualRate: 0,
  },
  imageField: {
    label: '资产字典照片',
    value: 'pictureList',
    fileType: ['jpg', 'png'],
    fileSize: 1,
    action: axios.defaults.baseURL + '/pub/uploadfile',
    btnDisabled: false,
  },
  fieldList: [
    {
      label: '资产字典名称',
      value: 'commonName',
      type: 'input',
    },
    { label: '资产字典编码', value: 'code', type: 'input', show: false },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'new_enabled_type',
    },
    {
      label: '医疗器械分类目录',
      value: 'deviceTypeValue',
      type: 'slot',
    },
    {
      label: '计量单位',
      value: 'unitId',
      type: 'select',
      list: 'unitList',
      filterable: true,
    },
    {
      label: '品牌',
      value: 'trademark',
      type: 'input',
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
    },
    {
      label: '资产分类',
      value: 'assetTypeValue',
      type: 'slot',
    },
    {
      label: '资产财务分类',
      value: 'financeTypeValue',
      type: 'slot',
    },
    {
      label: '折旧方法',
      value: 'deprMethodType',
      type: 'select-model',
      clearable: false,
      checkDefault: false,
      code: 'depr_method_type',
    },
    {
      label: '折旧惯例',
      value: 'deprConvention',
      type: 'select-model',
      clearable: false,
      checkDefault: false,
      code: 'depr_convention',
      show: true,
    },
    {
      label: '折旧月限',
      value: 'deprMonthsLimit',
      type: 'slot',
      min: 0,
      max: 999999,
      show: true,
    },

    {
      label: '强制收货验收',
      value: 'forceAccept',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    // {
    //   label: '是否入库管理',
    //   value: 'stockManage',
    //   type: 'radio-model',
    //   code: 'yes_or_no',
    // },
    {
      label: '设备标识',
      value: 'assetMark',
      type: 'select-model',
      clearable: true,
      multiple: true,
      code: 'assets_mark',
    },
    {
      label: '是否为计量资产',
      value: 'isMetering',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '是否维保',
      value: 'isMaintenance',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '是否医疗设备',
      value: 'isMedicalEquipment',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '报修预警时长(分钟)',
      value: 'repairWarnTime',
      labelTip:
        '该设备报修后超过设置分钟调度人员仍未派单则系统将自动通知调度员派单',
      type: 'number',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    commonName: [{ required: true, message: '请输入名称', trigger: 'change' }],
    code: [
      { required: true, message: '请输入编码', trigger: 'change' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    assetTypeValue: [
      { required: true, message: '请选择资产分类', trigger: 'change' },
    ],
    deprMonthsLimit: [
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    unitId: [
      {
        required:
          proxy.$store.state.permission.systemConfig.asset_unit_necessarily ==
          '1'
            ? true
            : false,
        message: '请选择计量单位',
        trigger: 'change',
      },
    ],
    deprMethodType: [
      { required: true, message: '请选择折旧方法', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
const licenseInfo = reactive({
  ref: null,
  data: {
    needLicense: 1,
  },
  fieldList: [
    {
      label: '是否关联证照',
      value: 'needLicense',
      type: 'radio-model',
      code: 'needLicense_type',
      required: true,
      show: true,
    },
    {
      label: '证号',
      value: 'licenseNumber',
      type: 'slot',
      required: true,
    },
    {
      label: '证照名称',
      value: 'licenseName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '英文名称',
      value: 'enName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '证照生效日期',
      value: 'licenseBeginDate',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '证照失效日期',
      value: 'licenseEndDate',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '生产厂家',
      value: 'brandName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '生产厂家',
      value: 'brandId',
      type: 'select',
      show: false,
      disabled: true,
      list: 'brandList',
      filterable: true,
      clearable: true,
    },
  ],
  rules: {
    licenseNumber: [
      { required: false, message: '请选择证号', trigger: 'change' },
    ],
  },
})
const selectSettingClassificationInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectSettingCategoryInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectAssetClassifyInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {},
})
const listTypeInfo = reactive({
  licenseList: [],
  brandList: [],
  unitList: [],
})
const selectLicenseInfo = reactive({
  visible: false,
  query: {
    status: '1',
    licenseApplicationType: 2,
  },
})
const isFirstUpdate = ref(false)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => licenseInfo.data.needLicense,
  (value) => {
    if (value == 1) {
      disabledFieldListItem(true, 'brandName')
      disabledFieldListItem(true, 'brandId')
      showLicenseFieldListItem(true, 'brandName')
      showLicenseFieldListItem(false, 'brandId')
      if (!isFirstUpdate.value) {
        licenseInfo.data['brandName'] = ''
        licenseInfo.data['brandId'] = ''
        licenseInfo.data['licenseTypeValue'] = ''
        licenseInfo.data['licenseName'] = ''
        licenseInfo.data['licenseBeginDate'] = ''
        licenseInfo.data['licenseEndDate'] = ''
        licenseInfo.data['enName'] = ''
        licenseInfo.data['licenseId'] = -2
        licenseInfo.data['licenseNumber'] = ''
      }
    } else if (value == 0) {
      disabledFieldListItem(false, 'brandName')
      disabledFieldListItem(false, 'brandId')
      showLicenseFieldListItem(false, 'brandName')
      showLicenseFieldListItem(true, 'brandId')
      console.log(isFirstUpdate.value)
      console.log(licenseInfo.data)
      if (!isFirstUpdate.value) {
        licenseInfo.data['brandName'] = ''
        licenseInfo.data['brandId'] = ''
        licenseInfo.data['licenseTypeValue'] = ''
        licenseInfo.data['licenseName'] = ''
        licenseInfo.data['licenseBeginDate'] = ''
        licenseInfo.data['licenseEndDate'] = ''
        licenseInfo.data['enName'] = ''
        licenseInfo.data['licenseId'] = -2
        licenseInfo.data['licenseNumber'] = ''
      }
      isFirstUpdate.value = false
    }
    // if (value == 1) {
    //   licenseInfo.rules.licenseNumber[0].required = true
    // } else if (value == 0) {
    //   licenseInfo.rules.licenseNumber[0].required = false
    // }
  }
)
watch(
  () => formInfo.data.deprMethodType,
  (value) => {
    //折旧方法
    if (value == '0') {
      //如果不折旧，那么隐藏所有跟折旧有关的值，并置为0
      showFieldListItem(false, 'deprConvention')
      showFieldListItem(false, 'deprMonthsLimit')
      formInfo.data.deprConvention = 0
      formInfo.data.deprMonthsLimit = 0
      formInfo.data.deprYearsLimit = 0
    } else {
      showFieldListItem(true, 'deprConvention')
      showFieldListItem(true, 'deprMonthsLimit')
    }
  }
)
onMounted(() => {
  setMedicalRepairWarnTime()
  getUnitList()
  getBrandList()
  getStatus()
  if (props.id) {
    isFirstUpdate.value = true
    getDeatil()
  }
})

//获取厂家列表
function getBrandList() {
  getBrandAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.brandList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
function showLicenseFieldListItem(show, nameValue) {
  licenseInfo.fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function disabledFieldListItem(enable, nameValue) {
  licenseInfo.fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.disabled = enable
    }
  })
}

function setMedicalRepairWarnTime() {
  let value = formInfo.data.isMedicalEquipment
  const systemConfig = proxy.$store.state.permission.systemConfig
  if (value == 1) {
    formInfo.data.repairWarnTime = systemConfig.medical_repair_warn_time
  } else if (value == 0) {
    formInfo.data.repairWarnTime = systemConfig.not_medical_repair_warn_time
  }
}
function getDeatil() {
  detailEquipmentArchives(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      formInfo.data = {
        commonName: data.commonName,
        code: data.code,
        unitId: data.unitId == -2 ? '' : data.unitId,
        standard: data.standard,
        status: data.status,
        remark: data.remark,
        trademark: data.trademark,
        financeType: data.financeType,
        financeTypeValue: data.financeTypeValue,
        forceAccept: data.forceAccept,
        // stockManage: data.stockManage,
        picture: data.picture,
        deviceType: data.deviceType,
        deviceTypeValue: data.deviceTypeValue,
        createUser: data.createUser,
        createTime: data.createTime,
        orgId: data.orgId,
        assetType: data.assetType,
        assetTypeValue: data.assetTypeValue,
        deprConvention: data.deprConvention,
        deprConventionValue: data.deprConventionValue,
        deprMethodType: data.deprMethodType,
        deprMethodTypeValue: data.deprMethodTypeValue,
        deprMonthsLimit: data.deprMonthsLimit % 12,
        deprYearsLimit: Math.floor(data.deprMonthsLimit / 12),
        assetMark: data.assetMark,
        isMetering: data.isMetering,
        isMaintenance: data.isMaintenance,
        isMedicalEquipment: data.isMedicalEquipment,
        repairWarnTime: data.repairWarnTime,
      }

      licenseInfo.data = {
        needLicense: data.needLicense,
        needLicenseValue: data.needLicenseValue,
        licenseNumber: data.licenseNumber,
        licenseTypeValue: data.licenseTypeValue,
        licenseName: data.licenseName,
        licenseBeginDate: data.licenseBeginDate,
        licenseEndDate: data.licenseEndDate,
        brandName: data.brandName,
        enName: data.enName,
        licenseId: data.licenseId,
        brandId: data.brandId == -2 ? '' : data.brandId,
      }
      if (formInfo.data.picture) {
        formInfo.data.pictureList = utils.splitArr(formInfo.data.picture)
      }
    }
  })
}
function save() {
  // let flag = 0
  formInfo.ref.validate((valid) => {
    console.log(valid, '1valid')
    if (valid) {
      // flag++
      licenseInfo.ref.validate((validate) => {
        if (validate) {
          const returnedTarget = Object.assign(formInfo.data, licenseInfo.data)
          if (
            returnedTarget.pictureList &&
            returnedTarget.pictureList.length == 1
          ) {
            returnedTarget.picture = returnedTarget.pictureList[0]
          } else {
            returnedTarget.picture = ''
          }
          if (props.id) {
            returnedTarget.id = props.id
          }
          const api = props.id
            ? updateEquipmentArchives
            : createEquipmentArchives
          api(returnedTarget).then((resp) => {
            if (resp && resp.success) {
              showDialog.value = false
              emits('returnModify')
              formInfo.ref.validateField()
            }
          })
        }
      })
    }
  })
}

function showFieldListItem(show, nameValue) {
  formInfo.fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
// 选择征照
function selectLicenseCallback(data) {
  proxy.$nextTick(function () {
    if (data) {
      console.log(data)
      licenseInfo.data = {
        ...licenseInfo.data,
        licenseNumber: data.licenseNumber,
        licenseTypeValue: data.licenseTypeValue,
        licenseName: data.licenseName,
        licenseBeginDate: data.licenseBeginDate,
        licenseEndDate: data.licenseEndDate,
        brandName: data.brandName,
        enName: data.enName,
        licenseId: data.id,
        brandId: data.brand,
      }
      disabledFieldListItem(true, 'brandName')
      disabledFieldListItem(true, 'brandId')
    } else {
      licenseInfo.data = {
        ...licenseInfo.data,
        licenseNumber: '',
        licenseTypeValue: '',
        licenseName: '',
        licenseBeginDate: '',
        licenseEndDate: '',
        brandName: '',
        enName: '',
        licenseId: -2,
        brandId: '',
      }
      if (licenseInfo.data.needLicense == 0) {
        disabledFieldListItem(false, 'brandName')
        disabledFieldListItem(false, 'brandId')
      } else {
        disabledFieldListItem(true, 'brandName')
        disabledFieldListItem(true, 'brandId')
      }
    }
  })
}
function getDepreciation(id) {
  getCategoryDetailsById(id).then((res) => {
    if (res && res.success) {
      let row = res.data
      formInfo.data.deprConvention = row.deprConvention
      formInfo.data.deprConventionValue = row.deprConventionValue
      formInfo.data.deprMethodType = row.deprMethodType
      formInfo.data.deprMethodTypeValue = row.deprMethodTypeValue
      // formInfo.data.deprMonthsLimit = row.deprMonthsLimit
      // formInfo.data.deprYearsLimit = row.deprYearsLimit
    }
  })
}
function selectAssetClassifyInfoCallBack(row) {
  if (row) {
    formInfo.data.assetType = row.id
    formInfo.data.assetTypeValue = row.name
    formInfo.data.financeType = row.assetFinancialClassifyId
    formInfo.data.financeTypeValue = row.assetFinancialClassifyName

    formInfo.data.deprMonthsLimit = row.deprMonthsLimit % 12
    formInfo.data.deprYearsLimit = Math.floor(row.deprMonthsLimit / 12)
    getDepreciation(row.assetFinancialClassifyId)
  } else {
    formInfo.data.assetType = -2
    formInfo.data.assetTypeValue = ''
    formInfo.data.financeType = -2
    formInfo.data.financeTypeValue = ''
    formInfo.data.deprConvention = ''
    formInfo.data.deprConventionValue = ''
    formInfo.data.deprMethodType = ''
    formInfo.data.deprMethodTypeValue = ''
    formInfo.data.deprMonthsLimit = ''
    formInfo.data.deprYearsLimit = ''
  }
}
function selectSettingCategoryInfoCallBack(row) {
  if (row) {
    formInfo.data.financeType = row.id
    formInfo.data.financeTypeValue = row.name
    formInfo.data.deprConvention = row.deprConvention
    formInfo.data.deprConventionValue = row.deprConventionValue
    formInfo.data.deprMethodType = row.deprMethodType
    formInfo.data.deprMethodTypeValue = row.deprMethodTypeValue
    formInfo.data.deprMonthsLimit = row.deprMonthsLimit
    formInfo.data.deprYearsLimit = row.deprYearsLimit
  } else {
    formInfo.data.financeType = -2
    formInfo.data.financeTypeValue = ''
    formInfo.data.deprConvention = ''
    formInfo.data.deprConventionValue = ''
    formInfo.data.deprMethodType = ''
    formInfo.data.deprMethodTypeValue = ''
    formInfo.data.deprMonthsLimit = ''
    formInfo.data.deprYearsLimit = ''
  }
}
function selectSettingClassificationInfoCallBack(row) {
  if (row) {
    formInfo.data.deviceType = row.id
    formInfo.data.deviceTypeValue = row.name
  } else {
    formInfo.data.deviceType = -2
    formInfo.data.deviceTypeValue = ''
  }
}
//获取计量单位列表
function getUnitList() {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
function openDeviceTypeWindow() {
  selectSettingClassificationInfo.visible = true
}
function openAssetClassifyWindow() {
  selectAssetClassifyInfo.visible = true
}
function openFinanceTypeWindow() {
  selectSettingCategoryInfo.visible = true
}
function openLicenseList() {
  selectLicenseInfo.visible = true
}
function getStatus() {
  getCoreCodeStatus({ codeType: '8' }).then((res) => {
    if (res && res.success) {
      showFieldListItem(!res.data, 'code')
      formInfo.rules.code[1].required = !res.data
    }
  })
}
</script>

<style scoped lang="scss">
.asset-setting-dict {
  :deep(.el-input-number.is-controls-right .el-input__wrapper) {
    padding-left: 5px;
  }
}
</style>
